package com.wlj.utils;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.BeanWrapper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

public class CBeanUtils {

    public static <T, R> List<R> copyArrayList(List<T> source, Function<T,R> function) {
        List list = new ArrayList();
        if (CollectionUtils.isEmpty(source)) {
            return new ArrayList<>();
        }
        for (T t : source) {
            R apply = function.apply(t);
            list.add(apply);
        }
        return list;
    }


    /**
     * 查询类中的空字段
     *
     * @param source 要查询的类
     * @return 空字段数据
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
